//
//  HotelQueryListController.swift
//  AirTravel
//
//  Created by apple on 2021/7/14.
//

import UIKit
import Moya
import SwiftyJSON

class HotelQueryListController: UIViewController {

    @IBOutlet weak var topLine: NSLayoutConstraint!
    @IBOutlet weak var topView: UIView!
    @IBOutlet weak var leaveTimeLab: UILabel!
    @IBOutlet weak var seachTf: UITextField!
    @IBOutlet weak var adressBtn: UIButton!
    @IBOutlet weak var stayTimeLab: UILabel!
    
    @IBOutlet weak var backView: UIView!
    /// 筛选
    @IBOutlet weak var screeningBtn: UIButton!
    /// 价格
    @IBOutlet weak var priceBtn: UIButton!
    /// 智能
    @IBOutlet weak var smartBtn: UIButton!
    /// 位置
    @IBOutlet weak var locationBtn: UIButton!
    
    @IBOutlet weak var tabView: UITableView!
    /// 用来主动取消网络请求
    var cancelableRequest: Cancellable?
    
    let identifyHL = "HotelListCell"
    var page = 1
    var currCity = ""
    var areaId = ""
    var cityId = ""
    var time1 = ""
    var time2 = ""
    var day = "0"
    //间数，成人，儿童
    var jian = "0"
    var cr = "0"
    var er = "0"
    ///酒店关键词
    var seachStr = ""
    
    /// 智能排序
    var sortList : Array<Any>?
    var sortDic : Dictionary<String,Any>?
    ///价格
    var priceList : Array<Any>?
    var priceDic : Dictionary<String,Any>?
    //星级
    var starDic : Dictionary<String,Any>?
    //位置距离
    var distanceList : Array<Any>?
    /// 酒店筛选位置类型 1机场 2火车站 3地铁 4酒店 5商圈 6地标 7行政区
    var hotelLocationType = ""
    /// 商圈
    var zoneCodeDic : Dictionary<String,Any>?
    /// 火车站
    var trainStationDic : Dictionary<String,Any>?
    /// 机场
    var airportDic : Dictionary<String,Any>?
    /// 地铁站
    var metroStationDic : Dictionary<String,Any>?
    /// 景点
    var viewSpotDic : Dictionary<String,Any>?
    
    /// 筛选
    var screenList : Array<Any>?
    /// 品牌
    var brandDic : Dictionary<String,Any>?
    /// 设施服务
    var facilityDic : Dictionary<String,Any>?
    var dataSouce = [NSDictionary]()
    var mutDataDic = Dictionary<Int, NSArray>()
    
    
    lazy var intelligentRankingView: HotelIntelligentRankingView = {
        let customPopupView = HotelIntelligentRankingView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 280))
        customPopupView.delegate = self
        return customPopupView
    }()
    
    lazy var positionDistanceView: PositionDistanceView = {
        let customPopupView = PositionDistanceView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 350))
        customPopupView.delegate = self
        return customPopupView
    }()
    
    lazy var priceStarView: PriceStarView = {
        let customPopupView = PriceStarView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 350))
        customPopupView.delegate = self
        return customPopupView
    }()
    
    lazy var screeningView: ScreeningView = {
        let customPopupView = ScreeningView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 450))
        customPopupView.delegate = self
        return customPopupView
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.isNavigationBarHidden = true
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        if SCREEN_HEIGHT >= 812 {
            self.topLine.constant = 88
        }else{
            self.topLine.constant = 64
        }
        self.backView.layer.cornerRadius = 20
        self.backView.layer.masksToBounds = true
        
        self.tabView.dataSource = self
        self.tabView.delegate = self
        self.tabView.rowHeight = 145
        self.tabView.tableFooterView = UIView.init()
        self.tabView.register(UINib.init(nibName: "HotelListCell", bundle: nil), forCellReuseIdentifier: identifyHL)
        
        self.adressBtn.setTitle(self.currCity, for: .normal)
        self.stayTimeLab.text = self.time1
        self.leaveTimeLab.text = self.time2
        self.seachTf.text = self.seachStr
        self.getHotelCondition()
        
        self.tabView.es.addPullToRefresh {[weak self] in
            self?.page = 1
            self?.searchHotelList()
        }
        
        self.tabView.es.addInfiniteScrolling {[weak self] in
            self?.page += 1
            self?.searchHotelList()
        }
        
    }

    @IBAction func backBtn(_ sender: UIButton) {
        self.navigationController?.popViewController(animated: true)
    }
    
    @IBAction func screening(_ sender: UIButton) {
        let btns = [self.smartBtn,self.locationBtn,self.priceBtn,self.screeningBtn]
        for item in btns {
            item?.isSelected = false
        }
        sender.isSelected = true
        switch sender.tag {
        case 0:
            self.intelligentRankingView.setUpData(array: self.sortList ?? [])
            self.headScreening(view: self.intelligentRankingView)
        case 1:
            if let array = self.distanceList {
                self.positionDistanceView.setUpData(array: array)
                self.headScreening(view: self.positionDistanceView)
            }
            
        case 2:
            if let array = self.priceList {
                self.priceStarView.setUpData(array: array)
                self.headScreening(view: self.priceStarView)
            }
        case 3:
            if let array = self.screenList {
                self.screeningView.setUpData(array: array)
                self.headScreening(view: self.screeningView)
            }
            
        default:
            break
        }
    }
    
    //获取酒店筛选条件
    func getHotelCondition() {
        cancelableRequest = NetWorkRequest(API1.getHotelCondition(parameters: ["cityId":self.cityId]), completion: {[weak self] (responseString) -> (Void) in
            self?.sortList = responseString["data"]["sortList"].arrayObject
            self?.priceList = responseString["data"]["priceList"].arrayObject
            self?.distanceList = responseString["data"]["distanceList"].arrayObject
            self?.screenList = responseString["data"]["screenList"].arrayObject
            
            self?.searchHotelList()
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常,超时")
        })
    }
    
    func searchHotelList() {
        var parameters = [String:String]()
        parameters.updateValue(self.cityId, forKey: "cityId")
        
        parameters.updateValue(self.time1, forKey: "checkInDate")
        parameters.updateValue(self.time2, forKey: "checkOutDate")
        
        let sortType = "\(self.sortDic?["id"] ?? "1")"
        parameters.updateValue(sortType, forKey: "sortType")
        parameters.updateValue("\(self.page)", forKey: "pageIndex")
        parameters.updateValue("10", forKey: "pageCount")
        let starType = "\(self.starDic?["id"] ?? "")"
        parameters.updateValue(starType, forKey: "starType")
        let minPrice = "\(self.priceDic?["min"] ?? "")"
        parameters.updateValue(minPrice, forKey: "minPrice")
        let maxPrice = "\(self.priceDic?["max"] ?? "")"
        parameters.updateValue(maxPrice, forKey: "maxPrice")
        parameters.updateValue(self.seachStr, forKey: "keyword")
        parameters.updateValue("", forKey: "brandId")
        
        switch self.hotelLocationType {
        case "1":
            parameters.updateValue("\(self.airportDic?["Infouid"] ?? "")", forKey: "airport")
        case "2":
            parameters.updateValue("\(self.trainStationDic?["Infouid"] ?? "")", forKey: "trainStation")
        case "3":
            parameters.updateValue("\(self.metroStationDic?["Infouid"] ?? "")", forKey: "metroStation")
        case "5":
            parameters.updateValue("\(self.zoneCodeDic?["Infouid"] ?? "")", forKey: "zoneCode")
//        case "4":
//            parameters.updateValue(self.seachStr, forKey: "keyword")
        case "6":
            parameters.updateValue("\(self.viewSpotDic?["Infouid"] ?? "")", forKey: "viewSpot")
        case "7":
            parameters.updateValue(self.areaId, forKey: "areaId")
        default:
            break
        }
        
        parameters.updateValue("", forKey: "facilityID")
        parameters.updateValue(self.hotelLocationType, forKey: "hotelLocationType")
        
        cancelableRequest = NetWorkRequest(API1.searchHotelList(parameters: parameters), completion: {[weak self] (responseString) -> (Void) in
            let data = responseString["data"]["hotelList"].arrayObject
            self?.tabView.es.stopPullToRefresh()
            self?.tabView.es.stopLoadingMore()
            if let array = data {
                self?.mutDataDic.updateValue((array as NSArray?)!, forKey: self!.page)
                self?.dataSouce.removeAll()
                for item in 1...self!.page {
                    let ar = (self?.mutDataDic[item] ?? []) as NSArray
                    for item in ar {
                        self?.dataSouce.append(item as! NSDictionary)
                    }
                }
            }else{
                self?.mutDataDic.updateValue(([]), forKey: self!.page)
                self?.dataSouce.removeAll()
                for item in 1...self!.page {
                    let ar = (self?.mutDataDic[item] ?? []) as NSArray
                    for item in ar {
                        self?.dataSouce.append(item as! NSDictionary)
                    }
                }
            }
            self?.tabView.reloadData()
        }, failed: { (failedResutl) -> (Void) in
            print("服务器返回code不为0000啦~\(failedResutl)")
        }, errorResult: { () -> (Void) in
            print("网络异常,超时")
        })
    }
    
    func headScreening(view:UIView) {
        GKCover.hideWithoutAnimation()
        let view1 = UIView.init()
        if SCREEN_HEIGHT >= 812 {
            view1.frame = CGRect.init(x: 0, y: 88 + 50, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 88 - 50)
        }else{
            view1.frame = CGRect.init(x: 0, y: 64 + 50, width: SCREEN_WIDTH, height: SCREEN_HEIGHT - 64 - 50)
        }
        view1.backgroundColor = UIColor.clear
        self.view.addSubview(view1)
        GKCover.cover(from: view1, contentView: view, style: .translucent, showStyle: .top, showAnimStyle: .none, hideAnimStyle: .none, notClick: false) {
            
        } hide: {
            view1.removeFromSuperview()
        }
    }
}

extension HotelQueryListController:HotelIntelligentRankingDelegate{
    func intelligentRankingClick(data: Dictionary<String, Any>) {
        GKCover.hideWithoutAnimation()
        self.sortDic = data
        self.smartBtn.setTitle("\(self.sortDic?["name"] ?? "")", for: .normal)
        self.tabView.header?.startRefreshing()
    }
}

extension HotelQueryListController:PositionDistanceDelegate{
    func positionDistanceClick(zoneCode: Dictionary<String, Any>, trainStation: Dictionary<String, Any>, airport: Dictionary<String, Any>, metroStation: Dictionary<String, Any>, viewSpot: Dictionary<String, Any>, hotelLocationType: String, hotel: String, areaId: String) {
        self.zoneCodeDic = zoneCode
        self.trainStationDic = trainStation
        self.airportDic = airport
        self.metroStationDic = metroStation
        self.viewSpotDic = viewSpot
        self.hotelLocationType = hotelLocationType
//        self.seachStr = hotel
        self.areaId = areaId
        self.tabView.header?.startRefreshing()
    }
    
}

extension HotelQueryListController:PriceStarDelegate{
    func priceStarClick(priceDic: Dictionary<String, Any>, starDic: Dictionary<String, Any>) {
        self.priceDic = priceDic
        self.starDic = starDic
//        self.tabView.reloadData()
        self.tabView.header?.startRefreshing()
    }
    
    
}

extension HotelQueryListController:ScreeningDelegate{
    func screeningClick(data: Dictionary<String, Any>) {
        
    }
}

extension HotelQueryListController:UITableViewDataSource,UITableViewDelegate{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataSouce.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: identifyHL) as! HotelListCell
        cell.selectionStyle = .none
        let dic = self.dataSouce[indexPath.row] as? Dictionary<String,Any>
        let firstImg = "\(dic?["firstImg"] ?? "")"
        cell.img.kf.setImage(with: URL.init(string: firstImg))
        cell.titleLab.text = "\(dic?["hotelName"] ?? "")"
        cell.reviewLab.text = "\(dic?["commentCount"] ?? "")人点评"
        
        let ctripCommRate = Double("\(dic?["ctripCommRate"] ?? "0")") ?? 0
        let ctripCommRateStr = String(format: "%.1f",ctripCommRate)
        cell.scoreBtn.setTitle("\(ctripCommRateStr)", for: .normal)
        cell.minPriceLab.text = "￥\(dic?["minPrice"] ?? "")"
        let zoneName = "\(dic?["zoneName"] ?? "")"
        if zoneName.isEmpty || zoneName == "<null>" {
            cell.distanceLab.text = "\(dic?["addressLine"] ?? "")"
        }else{
            cell.distanceLab.text = zoneName
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath){
        let vc = HotelDetailsController()
        vc.time2 = time2
        vc.time1 = time1
        vc.cityId = cityId
        
        let dic = self.dataSouce[indexPath.row] as? Dictionary<String,Any>
        vc.hotelId = "\(dic?["sourceHotelCode"] ?? "")"
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
}
